<script setup lang="tsx">
import type { VbenFormSchema } from '#/adapter/form';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { Anchor, Button, Col, Modal, Row } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { meetingAdd, meetingInfo, meetingUpdate } from '#/api/meeting';
import { tinymceHtmlExample } from '#/utils/html';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    // formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  scrollToFirstError: true,
  wrapperClass: 'grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2',
  fieldMappingTime: [
    [
      'time',
      ['startTime', 'endTime'],
      ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
    ],
  ],
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  contentClass: 'meeting-form',
  class: 'w-[70%]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id, type } = drawerApi.getData() as {
      id?: number | string;
      type?: number | string;
    };
    isUpdate.value = !!id;
    await formApi.setFieldValue('type', type);
    formApi.updateSchema([
      {
        fieldName: 'introduction',
        help: () => {
          return (
            <div class="flex flex-col items-center">
              <img
                alt=""
                class="mb-[10px] w-[120px]"
                src="https://resource.iteschina.com/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%A0%81/ITES%E5%B7%A5%E4%B8%9A%E5%B1%95/richtext-example.png"
              />
              <p class="mb-[10px]">扫码可查看示例效果展示</p>
              <Button onClick={meetingHtmlPrevewInsert} size="small">
                插入示例范文
              </Button>
            </div>
          );
        },
      },
    ]);

    if (isUpdate.value && id) {
      const record = await meetingInfo(id);
      if (record.startTime) {
        record.time = [record.startTime, record.endTime];
      }
      await formApi.setValues(record);
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? meetingUpdate(data) : meetingAdd(data));
    console.log(data);
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

// 插入会议富文本示例
function meetingHtmlPrevewInsert() {
  Modal.confirm({
    title: '提示',
    content: `将覆盖当前富文本编辑器里的内容，确认插入范文示例吗？`,
    onOk: async () => {
      await formApi.setFieldValue('introduction', tinymceHtmlExample);
    },
  });
}

// 锚点
const anchors = computed(() => {
  return drawerSchema()
    .filter((item: VbenFormSchema) => item.component === 'Divider')
    .map((item: any) => {
      return {
        key: item.fieldName,
        href: `#${item.componentProps?.id}`,
        title: item.renderComponentContent().default(),
      };
    });
});

function handleAnchorClick(e: any, link: any) {
  e.preventDefault();
  if (link?.href) {
    const el = document.querySelector(link.href);
    el?.scrollIntoView({ behavior: 'smooth' });
  }
}

function handleAnchorChange(link: string) {
  console.log('Anchor:OnChange', link);
}

function getContainer() {
  return document.querySelector('.meeting-form') as HTMLElement;
}
</script>

<template>
  <BasicDrawer :title="title">
    <Row :gutter="20">
      <Col :span="20">
        <div class="pb-[100px]">
          <BasicForm />
        </div>
      </Col>
      <Col :span="4">
        <Anchor
          affix
          :get-container="getContainer"
          :offset-top="50"
          :items="anchors"
          @click="handleAnchorClick"
          @change="handleAnchorChange"
        />
      </Col>
    </Row>
  </BasicDrawer>
</template>
